package com.wnhz.work.jy.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.OrderAdapter;
import com.wnhz.work.jy.bean.ShoppingBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;
import com.wnhz.work.jy.view.SwitchView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * -----下单
 */
public class OrderActivity extends BaseActivity implements View.OnClickListener, SwitchView.OnStateChangedListener {
    private static final String TAG = "OrderActivity";
    private static final int GET_ADDRESS = 100;

    private TextView title;
    private ImageView iv_pay_wei;
    private ImageView iv_pay_zhi;
    private ImageView iv_pay_yue;

    private LinearLayout linear;
    private ListView listView;
    private OrderAdapter mAdapter;

    //private List<OrderBean> orderList = new ArrayList<>();

    private ArrayList<ShoppingBean> list;
    private String jump;
    private TextView tv_total_prices;//合计
    private TextView explain;

    private LinearLayout ll_choose_web;//网点
    private RelativeLayout rl_address;//地址
    private RelativeLayout rl_address_show;//显示地址

    private TextView tv_address_name, tv_address_phone, tv_address_detail;

    private String obtainType;//类型
    private TextView tv_good_price;//商品价格
    private TextView tv_freight;//运费
    private TextView tv_favorable;//优惠

    private String allPrice;//总价

    private double goodprice;
    private double freight;
    private double favorable;
    private double allmoney;

    private String goodsId;//购物车id
    private String addressId;//选中的地址id
    private String name;
    private String phone;
    private String citys;
    private String areas;
    private String doorplate;
    private String addr;
    private TextView address_name, address_phone, toast, tv_addr;
    private String addressname;
    private ScrollView scrollView;

    private String addType;
    private SwitchView switchButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        list = (ArrayList<ShoppingBean>) getIntent().getSerializableExtra("list");
        setContentView(R.layout.activity_order);

        initData();
        initView();
        switchButton.setOpened(false);
        switchButton.setOnStateChangedListener(this);
    }

    private void initData() {
        jump = getIntent().getStringExtra("jump");
        obtainType = getIntent().getStringExtra("obtainType");
        allPrice = getIntent().getStringExtra("allPrice");
        addType = getIntent().getStringExtra("addType");
        goodsId = getIntent().getStringExtra("goodsId");
    }

    private void initView() {
        line = findViewById(R.id.line);
        ll_invoice = (LinearLayout) findViewById(R.id.ll_invoice);
        et_invoice = (EditText) findViewById(R.id.et_invoice);
        switchButton = (SwitchView) findViewById(R.id.switchButton);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        address_name = (TextView) findViewById(R.id.name);
        address_phone = (TextView) findViewById(R.id.tv_phone);
        toast = (TextView) findViewById(R.id.toast);
        tv_addr = (TextView) findViewById(R.id.tv_addr);
        title = (TextView) findViewById(R.id.view_main_middle_title);
        explain = (TextView) findViewById(R.id.tv_explain);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.rl_address).setOnClickListener(this);//地址
        findViewById(R.id.rl_wei).setOnClickListener(this);
        findViewById(R.id.rl_zhi).setOnClickListener(this);
        findViewById(R.id.rl_surplus).setOnClickListener(this);
        findViewById(R.id.tv_next).setOnClickListener(this);
        findViewById(R.id.rl_coupon).setOnClickListener(this);

        iv_pay_wei = (ImageView) findViewById(R.id.iv_pay_wei);
        iv_pay_zhi = (ImageView) findViewById(R.id.iv_pay_zhi);
        iv_pay_yue = (ImageView) findViewById(R.id.iv_pay_yue);
        tv_total_prices = (TextView) findViewById(R.id.tv_total_prices);//合计
        ll_choose_web = (LinearLayout) findViewById(R.id.ll_choose_web);
        rl_address = (RelativeLayout) findViewById(R.id.rl_address);
        rl_address.setOnClickListener(this);

        //add
        rl_address_show = (RelativeLayout) findViewById(R.id.rl_address_show);
        tv_address_name = (TextView) findViewById(R.id.tv_address_name);
        tv_address_phone = (TextView) findViewById(R.id.tv_address_phone);
        tv_address_detail = (TextView) findViewById(R.id.tv_address_detail);

        tv_good_price = (TextView) findViewById(R.id.tv_good_price);//商品价格
        tv_freight = (TextView) findViewById(R.id.tv_freight);//运费
        tv_favorable = (TextView) findViewById(R.id.tv_favorable);//优惠


        if ("1".equals(jump)) {
            title.setText("存入金库");
            ll_choose_web.setVisibility(View.GONE);
            rl_address.setVisibility(View.GONE);
        } else if ("2".equals(jump)) {
            title.setText("网点提取");
            rl_address.setVisibility(View.GONE);
        } else if ("3".equals(jump)) {
            title.setText("线下寄送");
            explain.setText("第二步：选择地址确认订单");
            ll_choose_web.setVisibility(View.GONE);
        }

        tv_good_price.setText(allPrice);
        /*goodprice = Double.parseDouble(tv_good_price.getText().toString());
        freight = Double.parseDouble(tv_freight.getText().toString());
        favorable = Double.parseDouble(tv_favorable.getText().toString());

        allmoney = goodprice + freight - favorable;*/

        tv_total_prices.setText("¥ " + allPrice);

        linear = (LinearLayout) findViewById(R.id.ll_goods);
        addListView(linear);
        scrollView.scrollTo(0, 0);
        scrollView.smoothScrollTo(0, 0);
    }

    private void addListView(LinearLayout linear) {
        View view = getLayoutInflater().inflate(R.layout.addorderlistview, null);
        listView = (ListView) view.findViewById(R.id.view_add_listview);

        mAdapter = new OrderAdapter(OrderActivity.this, list);
        listView.setAdapter(mAdapter);

        linear.addView(view);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
               finish();
                break;

            //选择收货地址
            case R.id.rl_address:
                intent = new Intent(OrderActivity.this, ChooseAddressActivity.class);
                startActivityForResult(intent, GET_ADDRESS);
                break;

            //优惠券
            case R.id.rl_coupon:
                intent = new Intent(OrderActivity.this, CouponActivity.class);
                startActivity(intent);
                break;

           /* //微信支付
            case R.id.rl_wei:
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze31_li3x);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze_nor3x);
                break;

            //支付宝
            case R.id.rl_zhi:
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze31_li3x);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze_nor3x);
                break;

            //余额
            case R.id.rl_surplus:
                iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor3x);
                iv_pay_yue.setImageResource(R.mipmap.ic_xuanze31_li3x);
                break;*/

            //下一步
            case R.id.tv_next:
                allprice = tv_total_prices.getText().toString();
                uploadByxUtils();
               /* String allprice = tv_total_prices.getText().toString();
                intent = new Intent(OrderActivity.this, PayActivity.class);
                intent.putExtra("allprice", allprice);
                intent.putExtra("obtainType", obtainType);
                intent.putExtra("list", list);
                if (null != addressId) {
                    intent.putExtra("addressId", addressId);
                }
                startActivity(intent);*/
                break;

            default:
                break;
        }
    }

    private String acedid;
    private String allprice;

    /**
     * addorder
     * 返回值 0代表缺少参数   1提交成功   2提交失败
     * 邮寄  1      提金币6    存金库0
     * 1支付宝支付  2微信支付 3银联 4积分兑换 5余额支付 7线下支付
     * $userId = I('post.userId');           //用户id
     * $obtainType = I('post.obtainType');   //配送方式
     * $addressId = I('post.addressId');     //地址id
     * $totalBank = I('post.totalBank');     //总行
     * $branchBank = I('post.branchBank');   //支行
     * $processing = I('post.processing');   //分处理
     * $couponId = I('post.couponId');       //优惠卷id
     * $paymoney = I('post.paymoney');       //支付总价
     * $payType = I('post.payType');         //支付方式
     * $cartids  = I('post.goods');          //购物车id
     */
    private void uploadByxUtils() {
        invoice = et_invoice.getText().toString();
        Map<String, Object> map = new HashMap<>();
        if ("1".equals(addType)) {
            map.put("goodsId", list.get(0).getGoodId());
            map.put("goodsNums", list.get(0).getGoodNumber());
        } else {
            for (int i = 0; i < list.size(); i++) {
                String id = list.get(i).getCartId();

                acedid = acedid + "_" + id;
            }

            acedid = acedid.substring(acedid.indexOf("_") + 1);
            map.put("goods", acedid);
        }

        Log.i(TAG, "uploadByxUtils: " + acedid);

        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("obtainType", obtainType);

        map.put("addType", addType);
        map.put("message", invoice);

        //线下寄送，有收获地址id
        if ("1".equals(obtainType)) {
            if (null != addressId) {
                map.put("addressId", addressId);
            } else {
                Toast.makeText(getApplication(), "请收货选择地址", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        showDialog();
        XUtil.Post(ConfigUtil.ADDORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: xiayibu" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    String orderid = jsonObject.optString("orderid");
                    if ("1".equals(res)) {
                        Intent intent = new Intent(OrderActivity.this, PayActivity.class);
                        intent.putExtra("orderid", orderid);
                        intent.putExtra("allprice", allprice);
                        startActivity(intent);
//                        Toast.makeText(OrderActivity.this, info, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(OrderActivity.this, info, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GET_ADDRESS) {
            if (resultCode == RESULT_OK) {
                if (null != data) {
                    addressId = data.getStringExtra("addressId");
                    addressname = data.getExtras().getString("name");
                    phone = data.getExtras().getString("phone");
                    citys = data.getExtras().getString("city");
                    areas = data.getExtras().getString("area");
                    doorplate = data.getExtras().getString("doorplate");
                    address_phone.setText(phone);
                    address_name.setText(addressname);
                    addr = citys + areas + doorplate;
                    toast.setVisibility(View.GONE);

                    tv_addr.setText(addr);
                }
            }
        }
    }

    @Override
    public void toggleToOn(View view) {
        switchButton.setOpened(true);
        line.setVisibility(View.VISIBLE);
        ll_invoice.setVisibility(View.VISIBLE);
    }
    private View line;
    private LinearLayout ll_invoice;
    private EditText et_invoice;
    private String invoice;
    @Override
    public void toggleToOff(View view) {
        switchButton.setOpened(false);
        line.setVisibility(View.GONE);
        ll_invoice.setVisibility(View.GONE);
        et_invoice.setText("");
    }
}
